<?php

namespace app\system\service;

use app\model\StockSetting;
use app\model\StockSettingTpl;
use app\traits\ServiceTrait;
use app\traits\UserTrait;
use think\helper\Arr;

class StockSettingService
{
    use UserTrait;
    use ServiceTrait;

    /**
     * @param $id
     * @return array
     */
    public function read($id): array
    {
        return [true, StockSetting::where(['stock_id' => $id])->findOrEmpty()->toArray()];
    }


    public function save(array $params, $adminId = 0): array
    {
        if (!$stockId = Arr::get($params, 'stock_id')) {
            return [false, '缺少必要参数stock_id'];
        }

        if (Arr::get($params, 'source') == 'api') {
            $pushTime = Arr::get($params, 'push_time');
            //查找要修改的id最早的修改时间
            $updatedAt = StockSetting::where(['stock_id' => $stockId])->order('updated_at', 'desc')->value('updated_at');
            if ($updatedAt > $pushTime) {
                return [false, '当前修改时间已经失效,请重试'];
            }
        }
        $model = StockSetting::where(['stock_id' => $stockId])->find() ?: (new StockSetting());
        //根据模板
        if ($tplId = Arr::get($params, 'tpl_id')) {
            if (!$tplModel = StockSettingTpl::where(['id' => $tplId])->field('ac_on_at,ac_off_at,timing_on,timing_off')->find()) {
                return [false, '模板id不存在'];
            }
            $tplModel->stock_id = $stockId;
            return [true, $model->save($tplModel)];
        }
        if (!Arr::get($params, 'auto_collect_time')) {
            $params['auto_collect_time'] = [];
        }
        $params['created_by'] = $this->getUid($adminId);
        $model->save($params);
        return [true, $model];
    }

    /**
     * 复制仓库设置
     * @param $from
     * @param $to
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function copy($data): array
    {
        if (!$from = Arr::get($data, 'from')) {
            return [false, '原仓库id不能为空'];
        }
        if (!$to = Arr::get($data, 'to')) {
            return [false, '目标仓库id不能为空'];
        }

        if (!$fromSetting = StockSetting::where(['stock_id' => $from])->findOrEmpty()) {
            return [false, '原仓库设置不能为空'];
        }
        unset($fromSetting['id']);
        $fromSetting['stock_id'] = $to;
        $model = StockSetting::where(['stock_id' => $to])->find() ?: (new StockSetting());
        $model->save($fromSetting);
        return [true, $model];
    }
}